﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace HobSoft.SoccerBet2014.Domain.Common.BfApi
{
    public class ApiJsonContent : HttpContent
    {
        public ApiJsonContent()
        {
            Encoding = System.Text.Encoding.UTF8;
            Headers.Add("content-type", "application/json");
        }
        public object Params
        {
            get;
            set;
        }

        public System.Text.Encoding Encoding { get; set; }

        protected int BufferLength { get; set; }
        protected byte[] SerializeJsonBuffer { get; set; }

        protected byte[] SerializeThisToJson()
        {
            var json = JsonConvert.SerializeObject(Params, Formatting.Indented);
            SerializeJsonBuffer = Encoding.GetBytes(json);
            BufferLength = SerializeJsonBuffer.Length;
            return SerializeJsonBuffer;
        }

        protected override Task<Stream> CreateContentReadStreamAsync()
        {
            if (BufferLength == 0)
                SerializeThisToJson();
            return Task.FromResult<Stream>(new MemoryStream(SerializeJsonBuffer, 0, BufferLength, false, false));
        }

        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            if (BufferLength == 0)
                SerializeThisToJson();
            return Task.Factory.FromAsync<byte[], int, int>(
                          new Func<byte[], int, int, AsyncCallback, object, IAsyncResult>(stream.BeginWrite)
                        , new Action<IAsyncResult>(stream.EndWrite), SerializeJsonBuffer, 0, BufferLength, null);
        }

        protected override bool TryComputeLength(out long length)
        {
            if (BufferLength == 0)
                SerializeThisToJson();
            length = BufferLength;
            return true;
        }
    }
}
